package com.czx.service.impl;

import com.czx.common.constants.RedisKeys;
import com.czx.service.FollowService;
import com.czx.vo.FollowerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

@Service
public class FollowServiceImpl implements FollowService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public int follower(FollowerVo followerVo) {
        ZSetOperations<String, String> zset = stringRedisTemplate.opsForZSet();
        String followKey = String.format(RedisKeys.USER_FOLLOWER_KEY, followerVo.getUserId());//关注人的key
        String fansKey = String.format(RedisKeys.USER_FANS_KEY, followerVo.getFollowerId());//被关注人的key
        System.out.println(followerVo.getFollowerId());
        //获取targetkey
        String targetKey = String.format(RedisKeys.USER_TARGET_KEY, followerVo.getFollowerId());
        //获取score，如果score有值说明已经点过赞了，那么就进行取消关注的操作
        Double score = zset.score(fansKey, followerVo.getUserId().toString());
        if (score != null) {
            zset.remove(followKey,followerVo.getFollowerId().toString());
            zset.remove(fansKey,followerVo.getUserId().toString());
            stringRedisTemplate.opsForValue().decrement(targetKey);
            return 1;
        }else {
            zset.add(followKey,followerVo.getFollowerId().toString(),System.currentTimeMillis());
            zset.add(fansKey,followerVo.getUserId().toString(),System.currentTimeMillis());
           stringRedisTemplate.opsForValue().increment(targetKey);
            return 0;
        }

    }

}
